<script setup lang="ts">
import { ref, onMounted } from "vue";
import { CircleClose, MoreFilled } from "@element-plus/icons-vue";
import CommonModal from "../components/modal/CommonModal.vue";
import { useRouter } from "vue-router";
import { getGoodsByStatus, updateServiceTime, deleteGoods } from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { useCreate } from "@/store/useCreate";

const createStore = useCreate();
const router = useRouter();
const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const currentStatus = ref(1); // 默认显示在售商品

// 获取商品列表
async function fetchGoodsList() {
  loading.value = true;
  try {
    const response = await getGoodsByStatus({
      queryStatus: currentStatus.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    console.error("获取商品列表失败:", error);
  } finally {
    loading.value = false;
  }
}

// 切换商品状态
function changeStatus(status: number) {
  currentStatus.value = status;
  currentPage.value = 1; // 重置页码
  fetchGoodsList();
}

// 页码变化处理
function handleCurrentChange(val: number) {
  currentPage.value = val;
  fetchGoodsList();
}

// 每页条数变化处理
function handleSizeChange(val: number) {
  pageSize.value = val;
  currentPage.value = 1; // 重置页码
  fetchGoodsList();
}

onMounted(() => {
  fetchGoodsList();
});

// 去创建商品
const createGoodsModalShow = ref(false);
const createGoods = () => {
  createGoodsModalShow.value = true;
};
const toCreate = () => {
  createStore.initFormData();
  createGoodsModalShow.value = false;
  router.push("/createCommodity");
};

// 更新服务时间
async function handleServiceTimeChange(goodsId: string, serverTimeType: number) {
  try {
    await updateServiceTime({ goodsId, serverTimeType });
    ElMessage.success("服务时间更新成功");
    fetchGoodsList(); // 重新获取列表数据
  } catch (error) {
    console.error("更新服务时间失败:", error);
    ElMessage.error("更新服务时间失败,请重试");
  }
}

// 删除商品
async function handleDeleteGoods(goodsId: string) {
  try {
    await ElMessageBox.confirm("确定要删除这个商品吗？此操作不可逆。", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await deleteGoods({ goodsId });
    ElMessage.success("商品删除成功");
    fetchGoodsList(); // 重新获取列表数据
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除商品失败:", error);
      ElMessage.error("删除商品失败,请重试");
    }
  }
}
// 编辑商品
const editGoodsModalShow = ref(false);
const handleEditGoods = (goodsId: string) => {
  createStore.initFormData();
  router.push(`/createCommodity?goodsId=${goodsId}`);
};
// 分享商品
const handleShareGoods = (goods: any) => {
  const str = `【技能猴子】http://jinenghouzi.com/details?id=${goods.id}
「${goods.goodsName}」
点击链接直接打开`;

  // 创建一个临时的textarea元素
  var textarea = document.createElement("textarea");
  textarea.value = str;

  // 避免屏幕闪烁
  textarea.style.position = "fixed";
  textarea.style.top = "-9999px";
  textarea.style.left = "-9999px";

  document.body.appendChild(textarea);
  textarea.focus();
  textarea.select();

  try {
    // 执行复制命令
    var successful = document.execCommand("copy");
    document.body.removeChild(textarea);
    ElMessage.success("已复制分享文字到剪贴板，快去分享吧");
  } catch (err) {
    document.body.removeChild(textarea);
  }
};
// 预览商品
const handlePreviewGoods = (goodsId: string) => {
  window.open(`http://jinenghouzi.com/details?id=${goodsId}`);
};
</script>

<template>
  <div class="goods-manage">
    <div class="tabs-box">
      <p class="tabs">
        <span :class="{ active: currentStatus === 1 }" @click="changeStatus(1)">
          在售商品
        </span>
        <span :class="{ active: currentStatus === 2 }" @click="changeStatus(2)">
          未上架
        </span>
      </p>
      <a @click="createGoods">+ 发布商品</a>
    </div>
    <view class="goods-list">
      <el-table class="goods-table" :data="tableData" v-loading="loading">
        <el-table-column label="技能商品" width="600px">
          <template #default="{ row }">
            <div class="goods-info">
              <img class="goods-img" :src="row.coverPic" alt="" />
              <p class="goods-name">{{ row.goodsName }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开启服务时间">
          <template #default="{ row }">
            <el-select
              v-model="row.serverTimeType"
              placeholder="请选择"
              style="width: 140px"
              @change="(value) => handleServiceTimeChange(row.id, value)"
            >
              <el-option v-if="row.status === 1" label="暂停销售" :value="0"></el-option>
              <el-option label="48小时内" :value="1"></el-option>
              <el-option label="7天内" :value="2"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <template v-if="row.status === 1">
              <el-text :style="{ color: 'rgb(29, 191, 115)' }"> 销售中 </el-text>
            </template>
            <template v-else>
              <el-text v-if="row.auditStatus === 0" style="color: rgba(25, 30, 40, 0.48)">
                待审核
              </el-text>
              <el-tooltip
                v-if="row.auditStatus === 2"
                class="box-item"
                :content="row.auditResult"
                placement="top-start"
              >
                <el-text style="color: #ff4f4f"
                  ><el-icon><CircleClose /></el-icon>审核未通过</el-text
                >
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div class="select-option">
              <el-text
                style="color: #1dbf73; margin-right: 10px; cursor: pointer"
                plain
                @click="handleEditGoods(row.id)"
                >编辑</el-text
              >
              <el-text
                v-if="row.status === 1"
                @click="handlePreviewGoods(row.id)"
                style="color: rgba(25, 30, 40, 0.48); margin-right: 10px; cursor: pointer"
                plain
                >预览</el-text
              >
              <el-dropdown trigger="click">
                <el-icon style="cursor: pointer" color="rgba(25, 30, 40, 0.48)"
                  ><MoreFilled
                /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleShareGoods(row)"
                      ><img class="select-icon" src="@/assets/more-select-1.png" alt="" />
                      分享</el-dropdown-item
                    >
                    <el-dropdown-item @click="handleDeleteGoods(row.id)"
                      ><img class="select-icon" src="@/assets/more-select-2.png" alt="" />
                      删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, prev, pager, next"
        />
      </div>
    </view>
  </div>
  <!-- 创建商品提示 -->
  <CommonModal
    title="新建商品"
    :show-cancel="false"
    confirm-text="开始创建"
    v-if="createGoodsModalShow"
    @close="createGoodsModalShow = false"
    @confirm="toCreate"
  >
    <template #content>
      <div class="create-modal">
        <p class="tips">
          热卖商品源于精心策划。巧妙地呈现你的专业技能并使之成为优质商品。
        </p>
        <h4 class="title">请仔细思考以下问题：</h4>
        <div class="line">
          <img src="@/assets/create-goods-icon1.png" alt="" />
          <p>
            <span>我有什么技能？</span>
            <span>描述描述描述描述描述描述描述</span>
          </p>
        </div>
        <div class="line">
          <img src="@/assets/create-goods-icon2.png" alt="" />
          <p>
            <span>我的技能可以解决买家什么需求？</span>
            <span>描述描述描述描述述描述描述</span>
          </p>
        </div>
        <div class="line">
          <img src="@/assets/create-goods-icon3.png" alt="" />
          <p>
            <span>买家为什么会选择我？</span>
            <span>描述描述描述描述描述描述描述</span>
          </p>
        </div>
      </div>
    </template>
  </CommonModal>
</template>

<style scoped lang="scss">
.goods-manage {
  flex: 1;
  overflow-y: auto;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 24px;
  box-sizing: border-box;
}
.tabs-box {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
  margin-bottom: 24px;
  .tabs {
    display: flex;
    align-items: center;
    span {
      margin-right: 40px;
      &.active {
        color: #1dbf73;
        font-weight: bold;
        position: relative;
        &:after {
          content: "";
          display: block;
          width: 100%;
          height: 2px;
          background: #1dbf73;
          position: absolute;
          bottom: -19px;
          left: 0;
        }
      }
    }
  }
  a {
    width: 108px;
    height: 36px;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    text-align: center;
    line-height: 36px;
    color: #fff;
    text-decoration: none;
    cursor: pointer;
  }
}
.goods-list {
  .goods-info {
    display: flex;
    align-items: center;
  }
  .goods-img {
    width: 90px;
    height: 60px;
    margin-right: 12px;
    border-radius: 8px;
  }
  .goods-name {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    height: 48px;
    line-height: 24px;
  }
}
.select-option {
  display: flex;
  align-items: center;
}
.select-icon {
  width: 16px;
  height: 16px;
  margin-right: 12px;
}
.create-modal {
  padding-top: 10px;
  .tips {
    margin-bottom: 16px;
  }
  .title {
    margin-bottom: 16px;
  }
  .line {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    img {
      width: 36px;
      height: 36px;
      margin-right: 10px;
    }
    p {
      display: flex;
      flex-direction: column;
      span:nth-child(1) {
        font-weight: bold;
        margin-bottom: 6px;
        font-size: 14px;
      }
      span:nth-child(2) {
        font-size: 12px;
        color: rgba(25, 30, 40, 0.6);
      }
    }
  }
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>

<style>
.goods-table {
  border: 1px solid #ccc;
  border-radius: 10px;
}
</style>
